import 'package:flutter/widgets.dart';
import 'package:x3_base_core/base_catalog/base_catalog_response_model.dart';
import 'package:x3_base_core/base_models/base_http_request_model.dart';
import 'package:x3_base_core/base_models/base_http_result_model.dart';
import 'package:x3_base_core/base_models/base_http_response_model.dart';

/**
 * 控制器
 */
class BaseCatalogController {

  /// 出参根据 appDisplay 获取模板
  static List<Widget> catalogResponseComponents(BaseHttpResultModel result, Map<String, Widget Function(BaseHttpResponseModel response, dynamic data)> catalog) {
    BaseCatalogResponseModel catalogModel = new BaseCatalogResponseModel(result);
    List<BaseHttpResponseModel> responses = catalogModel.response;
    List<Widget> _components = [];
    for (BaseHttpResponseModel response in responses) {
      String fieldName = response.fieldName;
      String appDisplay = response.appDisplay;
      var dataSource = catalogModel.findDataSource(fieldName);
      if (catalog.containsKey(appDisplay)) {
        _components.add(catalog[appDisplay](response, dataSource));
      }
    }
    return _components.toList();
  }

  /// 出参根据 fieldName 获取模板
  static List<Widget> catalogResponseFieldNameComponents(BaseHttpResultModel result, Map<String, Widget Function(BaseHttpResponseModel response, dynamic data)> catalog) {
    BaseCatalogResponseModel catalogModel = BaseCatalogResponseModel(result);
    List<BaseHttpResponseModel> responses = catalogModel.response;
    List<Widget> _components = [];
    for (BaseHttpResponseModel response in responses) {
      String fieldName = response.fieldName;
      var dataSource = catalogModel.findDataSource(fieldName);
      if (catalog.containsKey(fieldName)) {
        _components.add(catalog[fieldName](response, dataSource));
      }
    }
    return _components.toList();
  }

  /// 根据 inputType 获取模板
  static List<Widget> catalogFormComponents<T>(List<BaseHttpRequestModel> requests, Map<String, dynamic> dataSource, Map<T, Widget Function(BaseHttpRequestModel request, Map<String, dynamic> data)> catalog) {
    List<Widget> _components = [];
    for (BaseHttpRequestModel request in requests) {
      // 如果目录存在该组件则插入
      if (catalog.containsKey(request.inputType)) {
        _components.add(catalog[request.inputType](request, dataSource));
      }
    }
    return _components.toList();
  }

}
